#!/usr/bin/env ruby
$VERBOSE=true
require "rubygame"

require "rubygui"

def load_sound(name)
    return nil unless $sound_ok
    begin
        sound = Rubygame::Mixer::Sample.load_audio(name)
        return sound
    rescue Rubygame::SDLError
        puts "Cannot load sound " + name
        exit
    end
end

# This function is called when the program starts.It initializes
# everything it needs, then runs in a loop until the user closes
# the window or presses ESCAPE.
def main
	
	# Initialize Everything
	Rubygame.init()


	#check for dependencies
	puts 'Warning, images disabled' unless 
	  ($image_ok = (Rubygame::VERSIONS[:sdl_image] != nil))
	puts 'Warning, font disabled' unless 
	  ($font_ok = (Rubygame::VERSIONS[:sdl_ttf] != nil))
	puts 'Warning, sound disabled' unless
	  ($sound_ok = (Rubygame::VERSIONS[:sdl_mixer] != nil))
	puts "SDL_gfx is not available. Bailing out." unless 
	  ($gfx_ok = (Rubygame::VERSIONS[:sdl_gfx] != nil))
	puts "SDL_gfx version: #{Rubygame::VERSIONS[:sdl_gfx]}"

	screen = Rubygame::Screen.set_mode([800, 600])
	screen.title = 'GUI Demo 0'
	screen.show_cursor = false;
	# In rubygame, you make an EventQueue object; pygame just uses functions
	queue = Rubygame::EventQueue.new()
	Rubygame::Mixer::open_audio( 22050, 
                                 Rubygame::Mixer::AUDIO_U8,
                                 2,
                                 1024 )
	# Create The Background
	background = Rubygame::Surface.new(screen.size)
	background.fill([20,120,140])
	
	if $font_ok
		Rubygame::TTF.setup()

		font = Rubygame::TTF.new("FreeSans.ttf",25)
		text = font.render("GUI Demo 0", true, [10,10,10])
		textpos = Rubygame::Rect.new(0,0,*text.size)
		textpos.centerx = background.width/2
		text.blit(background,textpos)
	end
	
	punch_sound = load_sound('punch.wav')

	#Display The Background
	# Again, note the reversal of actors in the blit function
	background.blit(screen, [0,0])
	screen.update()
	
	#Prepare Game Objects
	clock = Rubygame::Clock.new { |clock| clock.target_framerate = 60 }

	#new GUI code
	ThemeManager.instance.load("theme/sample_theme.xml")
	ThemeManager.instance.set_default_theme(ThemeManager.instance.sample_theme.name)
	
	window=Window.new(screen.size)
	ResponderChain.instance.add_responder(window)

	
	puts "ThemeManager loaded: #{ThemeManager.instance.sample_theme.name}"

	root_panel=window.get_root_panel
	#vpanel=VerticalPanel.new(10)
	tabpanel=TabPanel.new
	button = Button.new("myButton", {
		:on_click=>lambda{|*args| 
			puts "myButton is clicked"
			Rubygame::Mixer::play(punch_sound,-1,0)
			}
		})
	label=Label.new("my label")
	
	hslider=HorizontalSlider.new
	hlabel=Label.new("0.0000")
	#link slider position to label text
	hslider.on_slider_changed.add_handler do|position|
		hlabel.set_text(((position-0.5)*2).to_s)
		button.move([(position-0.5)*2, 0])
	end
	
	vslider=VerticalSlider.new
	vlabel=Label.new("0.0000")
	#link slider position to label text
	vslider.on_slider_changed.add_handler do|position|
		vlabel.set_text(((position-0.5)*2).to_s)
		
		button.move([0,(position-0.5)*2])
	end
	panel=Panel.new([600,400])
	panel.add_child(label, [0,0])
	panel.add_child(button, [0, 50])
	panel.add_child(hslider, [0, 100])
	panel.add_child(hlabel, [0, 150])
	panel.add_child(vslider, [100, 0])
	panel.add_child(vlabel, [120, 0])
	tabpanel.add_tab(Label.new("my tab", ThemeManager.instance.default_theme.whitelabel), Frame.new(panel, ThemeManager.instance.default_theme.panel))

	#add textboxes to the tabpanel
	vpanel2=VerticalPanel.new(10)
	vpanel2.add_child(TextBox.new)
	vpanel2.add_child(TextBox.new)
	panel2=Panel.new([600,400])
	panel2.add_child(vpanel2, [0,0])
	frame=Frame.new(panel2, ThemeManager.instance.default_theme.panel)
	tabpanel.add_tab(Label.new("textboxes", ThemeManager.instance.default_theme.whitelabel), frame)
	
	#add images and labels to tabpanel
	hpanel=HorizontalPanel.new(10)
	vpanel0=VerticalPanel.new(10)
	vpanel0.add_child(Image.new("banana.bmp"))
	vpanel0.add_child(Label.new("my first banana"))
	vpanel1=VerticalPanel.new(10)
	vpanel1.add_child(Image.new("banana.bmp"))
	vpanel1.add_child(Label.new("my second banana"))
	hpanel.add_child(vpanel0)
	hpanel.add_child(vpanel1)
	panel3=Panel.new([600,400])
	panel3.add_child(hpanel, [0,0])
	tabpanel.add_tab(Label.new("images", ThemeManager.instance.default_theme.whitelabel), Frame.new(panel3, ThemeManager.instance.default_theme.panel))
	
	#add checkboxes to tabpanel
	vpanel3=VerticalPanel.new
	(0..5).each do |i|
		vpanel3.add_child(CheckBox.new(Label.new("option #{i}")))
	end
	panel4=Panel.new([600,400])
	panel4.add_child(vpanel3, [0,0])
	tabpanel.add_tab(Label.new("checkboxes", ThemeManager.instance.default_theme.whitelabel), Frame.new(panel4, ThemeManager.instance.default_theme.panel))
	#tabpanel.add_tab(Button.new("checkboxes", {}), Frame.new(panel3, ThemeManager.instance.default_theme.panel))
	
	#add radiobuttons to tabpanel
	radiogroup=RadioGroup.new
	(0..15).each do |i|
		radiogroup.add_option(Label.new("option #{i}"))
	end
	spanel=ScrollPanelwSlider.new(radiogroup, [200,100])
	panel5=Panel.new([600,400])
	panel5.add_child(spanel, [0,0])
	tabpanel.add_tab(Label.new("radiobuttons", ThemeManager.instance.default_theme.whitelabel), Frame.new(panel5, ThemeManager.instance.default_theme.panel))
	
	
	#add vpanel test to tabpanel
	l0=Label.new("VPanel")
	l1=Label.new("Text")
	l2=Label.new("Position")
	vpanel4=VerticalPanel.new(0)
	t0=TextBox.new
	t1=TextBox.new
	b0=Button.new("Add")
	b0.on_click.add_handler do
		text=t0.get_text
		position=t1.get_text.to_i
		if not position.nil?
			vpanel4[position]=Label.new(text)
		end
		l0.set_text("Vpanel: ["+vpanel4.rect.x.to_s+","+vpanel4.rect.y.to_s+"]")
	end
	panel6=Panel.new([600,400])
	panel6.add_child(l0, [0,0])
	panel6.add_child(vpanel4, [0,20])
	
	panel6.add_child(l1, [300, 0])
	panel6.add_child(t0, [400, 0])
	panel6.add_child(l2, [300, 50])
	panel6.add_child(t1, [400, 50])
	panel6.add_child(b0, [480, 100])
	
	tabpanel.add_tab(Label.new("tables", ThemeManager.instance.default_theme.whitelabel), Frame.new(panel6, ThemeManager.instance.default_theme.panel))
	
	
	
	root_panel.add_child(tabpanel, [10,50])
	
	puts "vpanel4 pos: #{vpanel4.rect.x}, #{vpanel4.rect.y}"
	
	
	#add quit button
	quitbutton = Button.new("Quit", {
		:on_click=>lambda{|*args| 
			Rubygame.quit()
			}
		})
	quitbutton.on_mouse_up.add_handler {exit}
	root_panel.add_child(quitbutton, [700,20])
	
	#TODO create a GUI example that tests all gui classes and looks good too :)
	
	#Main Loop
	loop do
		clock.tick()
		
		#Handle Input Events
		# Iterate through all the events the Queue has caught
		queue.each do |event|
			# Perform hardcoded actions
			case(event)
			when Rubygame::QuitEvent
				return			# break out of the main function
			when Rubygame::KeyDownEvent
				case event.key 
				when Rubygame::K_ESCAPE
					return			# break out of the main function
				end
			end
			#forward the event to the responder chain
			nil.process_event(event)
		end 					# end event handling

		nil.update()
		

    #Draw Everything
		background.blit(screen, [0, 0])
		nil.draw(screen)
		screen.update()

		screen.title = '%d'%clock.framerate
	end							# end loop

	#Game Over
ensure
  # This ensures that we properly close and clean up everything at the end
  # of the game.
	Rubygame::Mixer.close_audio()
	Rubygame.quit()
end								# end main function


#this calls the 'main' function when this script is executed
if $0 == __FILE__
	main()
end
